﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SuperORM;
using System.Data;

namespace Helper
{
    public class SessionHelper
    {
        #region 初始化Session
        public static ISession InitSessionFromSQLMeta(string server, string metadb, string userid, string password)
        {
            SuperORM.cfg.Configuration cfg = new SuperORM.cfg.Configuration();
            SuperORM.ISessionFactory factory = cfg.BuildSessionFactory();
            ISession session = factory.OpenSession();

            NamedDataSource ds = new NamedDataSource();
            ds.Name = "META";
            ds.DataDriverType = SuperORM.Driver.SqlClientDriver.Name;
            ds.ConnectionString = string.Format("User ID= {0};Initial Catalog= {2};Data Source={3};Pwd={1};Connection Timeout=360;", userid, password, metadb, server);
            session.AddDatasource(ds);
            SmQuery qry = session.CreateSmQuery("META");
            DataRowCollection drc = qry.GetDataRowsBySQL("select * from meta_ds where YXBZ=1");
            if (drc != null && drc.Count > 0)
            {
                for (int i = 0; i < drc.Count; i++)
                {
                    string uid = drc[i]["USERNAME"].ToString();
                    string pwd = drc[i]["PASSWORD"].ToString();
                    string db = drc[i]["DBMC"].ToString();
                    string ser = drc[i]["SERVER"].ToString();
                    string dblx = drc[i]["DBLX"].ToString();
                    string dsbm = drc[i]["DSBM"].ToString();
                    if (dblx == "1")
                    {
                        NamedDataSource ds2 = new NamedDataSource();
                        ds2.DataDriverType = SuperORM.Driver.SqlClientDriver.Name;
                        ds2.ConnectionString = string.Format("User ID= {0};Initial Catalog= {2};Data Source={3};Pwd={1};Connection Timeout=360;", uid, pwd, db, ser);
                        ds2.Name = dsbm;
                        session.AddDatasource(ds2);
                    }
                    else
                    {
                        NamedDataSource ds2 = new NamedDataSource();
                        ds2.DataDriverType = SuperORM.Driver.OracleClientDriver.Name;
                        ds2.ConnectionString = string.Format("user id= {0};Data Source={2};password={1};Unicode=True", uid, pwd, ser);
                        ds2.Name = dsbm;
                        session.AddDatasource(ds2);
                    }
                }
            }
            session.FlushMode = SuperORM.FlushMode.Never;
            return session;
        }
        #endregion

    }
}